package com.example.springbootdemo.controller;

import com.example.springbootdemo.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/files")
@CrossOrigin(origins = "*")
public class MinioController {
    
    @Autowired
    private MinioService minioService;
    
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件大小
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "error", "文件为空",
                    "message", "请选择要上传的文件"
                ));
            }
            
            // 检查文件大小 (10MB = 10 * 1024 * 1024 bytes)
            long maxSize = 10 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return ResponseEntity.badRequest().body(Map.of(
                    "error", "文件过大",
                    "message", "文件大小不能超过10MB，当前文件大小: " + formatFileSize(file.getSize())
                ));
            }
            
            String fileName = minioService.uploadFile(file);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "fileName", fileName,
                "message", "文件上传成功"
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "error", "上传失败",
                "message", "文件上传失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 从OSS下载并上传到MinIO
     */
    @PostMapping("/oss-download-upload")
    public ResponseEntity<Object> downloadAndUploadFromOss(@RequestBody Map<String, String> request) {
        try {
            String ossUrl = request.get("url");
            if (ossUrl == null || ossUrl.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "error", "参数错误",
                    "message", "OSS资源地址不能为空"
                ));
            }
            
            String fileName = minioService.downloadAndUploadFromOss(ossUrl);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "fileName", fileName,
                "message", "文件下载并上传成功"
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "error", "操作失败",
                "message", "下载并上传失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取文件列表
     */
    @GetMapping("/list")
    public ResponseEntity<List<MinioService.FileInfo>> listFiles() {
        try {
            List<MinioService.FileInfo> files = minioService.listFiles();
            return ResponseEntity.ok(files);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }
    
    /**
     * 删除文件
     */
    @DeleteMapping("/{fileName}")
    public ResponseEntity<String> deleteFile(@PathVariable String fileName) {
        try {
            minioService.deleteFile(fileName);
            return ResponseEntity.ok("文件删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("文件删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件下载预签名URL
     */
    @GetMapping("/download-url/{fileName}")
    public ResponseEntity<Map<String, Object>> getDownloadUrl(@PathVariable String fileName) {
        try {
            String url = minioService.getPresignedUrl(fileName);
            return ResponseEntity.ok(Map.of("url", url));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "获取下载链接失败", "message", e.getMessage()));
        }
    }
    
    /**
     * 格式化文件大小
     */
    private String formatFileSize(long bytes) {
        if (bytes < 1024) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(1024));
        String pre = "KMGTPE".charAt(exp-1) + "";
        return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
    }
} 